<!DOCTYPE html>






<html class="theme-next muse use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">







  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">


















  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">



















































<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.3" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.3">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.3" color="#222">





  <meta name="keywords" content="Groovy,">










<meta name="description" content="前面MOP——方法拦截介绍了利用 MOP 对方法的调用进行拦截，接下来要介绍利用 MOP 实现方法的注入。 方法拦截和方法注入的区别拦截：侧重对于已有的方法的调用进行拦截注入：对一个已有的类添加新方法，以拓展该类的功能。 eg：Java 中提供了 String 的类，如果我们想扩展该类，为其提供一个字符串加密方法。在 Java 中，最常见的做法是提供一个接口，内有 encrypt() 方法，让目标">
<meta name="keywords" content="Groovy">
<meta property="og:type" content="article">
<meta property="og:title" content="MOP——方法注入">
<meta property="og:url" content="https://zachaxy.github.io/2017/12/10/MOP——方法注入/index.html">
<meta property="og:site_name" content="zachaxy">
<meta property="og:description" content="前面MOP——方法拦截介绍了利用 MOP 对方法的调用进行拦截，接下来要介绍利用 MOP 实现方法的注入。 方法拦截和方法注入的区别拦截：侧重对于已有的方法的调用进行拦截注入：对一个已有的类添加新方法，以拓展该类的功能。 eg：Java 中提供了 String 的类，如果我们想扩展该类，为其提供一个字符串加密方法。在 Java 中，最常见的做法是提供一个接口，内有 encrypt() 方法，让目标">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2019-09-01T11:13:24.296Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="MOP——方法注入">
<meta name="twitter:description" content="前面MOP——方法拦截介绍了利用 MOP 对方法的调用进行拦截，接下来要介绍利用 MOP 实现方法的注入。 方法拦截和方法注入的区别拦截：侧重对于已有的方法的调用进行拦截注入：对一个已有的类添加新方法，以拓展该类的功能。 eg：Java 中提供了 String 的类，如果我们想扩展该类，为其提供一个字符串加密方法。在 Java 中，最常见的做法是提供一个接口，内有 encrypt() 方法，让目标">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '5.1.3',
    sidebar: {"position":"right","display":"hide","offset":12,"b2t":false,"scrollpercent":true,"onmobile":true},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: 'undefined',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://zachaxy.github.io/2017/12/10/MOP——方法注入/">





  <title>MOP——方法注入 | zachaxy</title>









</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">






  <div class="container sidebar-position-right page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">


    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">zachaxy</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>

        <h1 class="site-subtitle" itemprop="description">纵情向前！</h1>

  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">



    <ul id="menu" class="menu">


        <li class="menu-item menu-item-home">
          <a href="/" rel="section">

              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>

            首页
          </a>
        </li>


        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">

              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>

            标签
          </a>
        </li>


        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">

              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>

            归档
          </a>
        </li>


        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">

              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>

            关于
          </a>
        </li>



        <li class="menu-item menu-item-search">

            <a href="javascript:;" class="popup-trigger">


              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>

            搜索
          </a>
        </li>

    </ul>



    <div class="site-search">

  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>

</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">


  <div id="posts" class="posts-expand">








  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">



  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zachaxy.github.io/2017/12/10/MOP——方法注入/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="zachaxy">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="zachaxy">
    </span>


      <header class="post-header">



          <h2 class="post-title" itemprop="name headline">MOP——方法注入</h2>


        <div class="post-meta">
          <span class="post-time">

              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>

                <span class="post-meta-item-text">发表于</span>

              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-12-10T11:45:09+08:00">
                2017-12-10
              </time>





          </span>













            <div class="post-wordcount">


                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>

                  <span class="post-meta-item-text">字数统计&#58;</span>

                <span title="字数统计">
                  2,358
                </span>





            </div>




        </div>
      </header>





    <div class="post-body" itemprop="articleBody">





        <p>前面<a href="https://zachaxy.github.io/2017/12/09/MOP%E2%80%94%E2%80%94%E6%96%B9%E6%B3%95%E6%8B%A6%E6%88%AA/">MOP——方法拦截</a>介绍了利用 MOP 对方法的调用进行拦截，接下来要介绍利用 MOP 实现方法的注入。</p>
<h1 id="方法拦截和方法注入的区别"><a href="#方法拦截和方法注入的区别" class="headerlink" title="方法拦截和方法注入的区别"></a>方法拦截和方法注入的区别</h1><p>拦截：侧重对于<strong>已有的方法</strong>的调用进行拦截<br>注入：对一个已有的类<strong>添加新方法</strong>，以拓展该类的功能。</p>
<p>eg：Java 中提供了 String 的类，如果我们想扩展该类，为其提供一个字符串加密方法。在 Java 中，最常见的做法是提供一个接口，内有 encrypt() 方法，让目标类实现该接口；或者继承该类，然后添加一个 encrypt() 方法。但是这里存在的问题是：我们未必可以修改想要扩展的类，就像 String，还是 final 的，只能用，不能改。</p>
<p>不过使用 Groovy，就可以方便的为任何类扩展方法，同时在使用起来，给人的感觉就好像注入的类是该类本身就有的。</p>
<p>MOP 的注入有四种实现方式：</p>
<ol>
<li>分类(Category)</li>
<li>ExpandoMetaClass</li>
<li>Minxin</li>
<li>trait</li>
</ol>
<a id="more"></a>

<h1 id="使用分类进行方法注入"><a href="#使用分类进行方法注入" class="headerlink" title="使用分类进行方法注入"></a>使用分类进行方法注入</h1><p>第一次接触 Category 的概念是在学习 Objective-C 的时候，只要自定义一个和目标类相同的类，然后在自定义类中添加方法，那么在方法调用时，会先从自定义的类中查找，找不到后再去原本的类中查找。这样一来不仅可以扩展类的方法，同时还可以覆盖原有类的方法。Objective-C 中 Category 感觉是最优雅的方式了。而 Groovy 中的 Category 就逊色的多，接下来看一下 Groovy 中 Category 的使用方法，这里以向 String 中添加一个 encrypt 方法为例。</p>
<figure class="highlight groovy"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">StringUtils</span> &#123;</span></span><br><span class="line">    <span class="keyword">def</span> <span class="keyword">static</span> encrypt(String self) &#123;</span><br><span class="line">        <span class="keyword">byte</span>[] arr = self.bytes;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; arr.length; i++) &#123;</span><br><span class="line">            arr[i] = (<span class="number">127</span> - arr[i])</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> String(arr)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">IntegerUtils</span>&#123;</span></span><br><span class="line">    <span class="keyword">def</span> <span class="keyword">static</span> add(Integer a, <span class="keyword">int</span> b) &#123;</span><br><span class="line">        a + b</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">use(StringUtils,IntegerUtils) &#123;</span><br><span class="line">    String str = <span class="string">"hello"</span></span><br><span class="line">    s = str.encrypt()</span><br><span class="line">    println <span class="number">1.</span>add(<span class="number">2</span>)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这里先定义了一个的类，其中定义了一个方法 encrypt(),要想要该类成为 String 的分类，需要注意以下几点：</p>
<ol>
<li>其内部定义的方法必须为 <code>static</code></li>
<li>方法的第一个参数必须定位为目标类的类型(eg：这里定义的 String，当然你可以不写类型，这样就有可能让多个类都是用该方法了),如果该方法还需要参数，那么就从第二个形参开始声明。</li>
<li>第一个参数如果声明类型，必须为包装类的类型，eg：如果我们想为整数提供方法，即使用到了 <code>1.add(2)</code> 这样的调用方式，但这是 groovy 提供的语法糖，其本质任为 Integer，因此在定义分类的方法时，第一个参数必须是包装类型</li>
</ol>
<p>在使用时，其必须在 use 所定义的代码块中，出了代码块就无法使用分类中的方法了，否则报找不到方法的错误。在 use 后面必须注明要注入的方法所在的类，eg：use(StringUtils)，use 中可以注入多个类，如果多个分类中有重复的方法定义，那么以最后一个分类中方法为准。</p>
<h1 id="使用-ExpandoMetaClass-进行方法注入"><a href="#使用-ExpandoMetaClass-进行方法注入" class="headerlink" title="使用 ExpandoMetaClass 进行方法注入"></a>使用 ExpandoMetaClass 进行方法注入</h1><h2 id="注入概述"><a href="#注入概述" class="headerlink" title="注入概述"></a>注入概述</h2><p>之前其实我们已经见到过使用 ExpandoMetaClass 注入方法的示例了，就是使用<a href>MetaClass 进行方法拦截</a>，这本质就是方法的注入，只不过注入的方法名(invokeMethod)比较特殊，成为了方法拦截。同样，我们也可以用 ExpandoMetaClass 对类进行其它方法的注入，还拿上面 Integer 的加法的例子：</p>
<figure class="highlight groovy"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">Integer.metaClass.add = &#123;</span><br><span class="line">    <span class="keyword">int</span> i -&gt;</span><br><span class="line">        delegate + i</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">println <span class="number">1.</span>add(<span class="number">3</span>)</span><br></pre></td></tr></table></figure>

<h2 id="注入的种类"><a href="#注入的种类" class="headerlink" title="注入的种类"></a>注入的种类</h2><p>使用 ExpandoMetaClass 方法注入，可以对以下三种方法进行注入：</p>
<ul>
<li>非静态方法</li>
<li>静态方法</li>
<li>构造器</li>
<li>属性</li>
</ul>
<p>接下来一一介绍如何注入：</p>
<ol>
<li><p>非静态方法注入<br>这在前面已经见到过了，也是最常用的注入，使用方法：</p>
<figure class="highlight groovy"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Foo.metaClass.bar = &#123;&#125;</span><br><span class="line">foo.bar()</span><br></pre></td></tr></table></figure>

<p>Groovy 的设计理念就是让程序的编写更加流程，因此在 DSL 中，可能更常见的一种形式是在调用方法时不写括号，即<code>foo.bar</code>但是没有括号调用时，会将方法的调用当成属性，所以需要对之前的注入进行修改。</p>
<figure class="highlight groovy"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Foo.metaClass.getBar = &#123;&#125;</span><br><span class="line">foo.bar</span><br></pre></td></tr></table></figure>

<p>这样的调用方式是否更加优雅呢，在后面的 DSL 中，还会进一步讲解 groovy 的语法糖，让编程更加优雅。</p>
</li>
<li><p>静态方法注入<br>需要使用 <code>&#39;static&#39;</code> 的特殊字面量注入静态方法</p>
<figure class="highlight groovy"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Foo.metaClass.<span class="string">'static'</span>.bar = &#123;&#125;</span><br><span class="line">Foo.bar()</span><br></pre></td></tr></table></figure>
</li>
<li><p>注入构造器<br>使用 <code>constructor</code> 属性注入构造器<br>添加一个构造器 &lt;&lt;<br>替换一个构造器 =</p>
<figure class="highlight groovy"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">Foo.metaClass.constructor &lt;&lt; &#123; </span><br><span class="line">	<span class="keyword">int</span> i -&gt; </span><br><span class="line">	Foo foo = <span class="keyword">new</span> Foo();</span><br><span class="line">	foo.i = i</span><br><span class="line">	foo</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>构造方法注入特别要注意的是，要确保没有递归调用自身，否则栈溢出。因为我们是想定义构造器，肯定会借助现有的构造器，然后进行属性的改造，但是不要产生递归。如果是想覆盖构造器的话，那么只能在内部使用反射</p>
</li>
<li><p>注入属性<br>类似以闭包的方式注入方法，属性注入也是支持的，只要在后面 = 具体值 即可。</p>
<figure class="highlight groovy"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Foo.metaClass.bar = <span class="number">1</span></span><br><span class="line">println foo.bar</span><br></pre></td></tr></table></figure>
</li>
<li><p>一次注入多个方法<br>Groovy 提供了使用<code>ClassName.metaClass.method = { ... }</code>这样的语法向 metaClass 中添加，既简单又方便，但如果想添加一堆方法，这样的声明就会感觉很费劲。groovy 提供了更简洁的语法，用来减少噪音！！这种方式也是在 DSL 中常见到的。</p>
<figure class="highlight groovy"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">Foo.metaClass = &#123;</span><br><span class="line">	bar1 = &#123;&#125;</span><br><span class="line">	bar2 = &#123;&#125;</span><br><span class="line"></span><br><span class="line">	<span class="string">'static'</span>&#123;</span><br><span class="line">		bar3 = &#123;&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="comment">//针对于不管是覆盖还是注入，在这种语法环境下，都应该使用 = </span></span><br><span class="line">	constructor = &#123;</span><br><span class="line">		<span class="keyword">int</span> i - &gt;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	constructor = &#123;</span><br><span class="line">		<span class="keyword">int</span> i,<span class="keyword">int</span> j -&gt;</span><br><span class="line"></span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

</li>
</ol>
<p><strong>再次重申：使用 ExpandoMetaClass 注入的闭包中，delegate 指的是调用该方法的对象，在此基础上，闭包中使用类原本的成员变量，或者方法也是可以的。</strong></p>
<h2 id="向单个实例中注入方法"><a href="#向单个实例中注入方法" class="headerlink" title="向单个实例中注入方法"></a>向单个实例中注入方法</h2><p>前面介绍的是向整个类中注入方法，那么基于该类的所有对象都可以使用闭包中的方法。如果只是想扩展该类的某一个对象的方法，而不影响该类的其它对象，该如何处理呢？<br>其实不单是 Class，每个具体的对象也包含一个 metaClass，我们可将创建一个具体的 ExpandoMetaClass 实例，并将制定方法加入其中，然后将其赋给对应的具体对象，也可以将方法直接注入到具体的对象的 metaClass 上。</p>
<figure class="highlight groovy"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//方式 1</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Man</span>&#123;</span></span><br><span class="line">	<span class="keyword">def</span> talk()&#123;&#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">def</span> emc = <span class="keyword">new</span> ExpandoMetaClass(Man)</span><br><span class="line">emc.sing = &#123; -&gt; ... &#125;</span><br><span class="line">emc.initialize()</span><br><span class="line"><span class="keyword">def</span> mike = <span class="keyword">new</span> Man()</span><br><span class="line">mile.metaClass = emc</span><br><span class="line">mike.sing()</span><br><span class="line"></span><br><span class="line"><span class="comment">//方式 2</span></span><br><span class="line">mike.metaClass.dance = &#123; -&gt; ...&#125;</span><br><span class="line">mike.dance()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">//卸载之前注入的方法</span></span><br><span class="line">mike.metaClass = <span class="literal">null</span></span><br></pre></td></tr></table></figure>

<p>很明显方式 2 是最为优雅的，因此推荐使用方式 2。同时，当我们为一个对象注入了方法，在使用了一段时间不想使用后，那么很方便的卸载之前注入的方法。</p>
<h2 id="ExpandoMetaClass-小结"><a href="#ExpandoMetaClass-小结" class="headerlink" title="ExpandoMetaClass 小结"></a>ExpandoMetaClass 小结</h2><p>使用 ExpandoMetaClass，无论是注入方法，还是调用方法，都比 Category 要优雅的多。因此推荐使用该方法。<br>但是要注意的是，如果对象想使用注入的方法，必须要先进行注入。如果在已经有对象产生之后再向类中注入方法，那么该对象无法调用注入的方法！！<br>因此使用 ExpandoMetaClass 进行注入，最好是在整个应用初始化时进行。</p>
<p>同时方法注入具有继承性。如果向 Object 注入了方法，那么所有的类都可以使用该方法。</p>
<h1 id="使用-Minxin，trait-进行方法注入"><a href="#使用-Minxin，trait-进行方法注入" class="headerlink" title="使用 Minxin，trait 进行方法注入"></a>使用 Minxin，trait 进行方法注入</h1><p>这两种方式更像是开头提到的定义接口的实现方式。<br>个人感觉最为强大的方式是 Mixin 的方式。可以为类注入多个 Mixin，就好想让类实现了多个接口，同时接口中相同的方法，以后面加入的为准。<br>这里不再重点展开了。<br><a href="http://blog.csdn.net/chennai1101/article/details/56282305" target="_blank" rel="noopener">Groovy Mixin 注入</a><br><a href="https://www.mscharhag.com/groovy/groovy-introduces-traits" target="_blank" rel="noopener">Groovy 2.3 introduces traits</a><br><a href="https://www.ibm.com/developerworks/library/j-jn8/index.html" target="_blank" rel="noopener">Mixins and traits</a></p>
<h1 id="实现方式的优劣对比"><a href="#实现方式的优劣对比" class="headerlink" title="实现方式的优劣对比"></a>实现方式的优劣对比</h1><ul>
<li><p>Category 存在的问题:其作用被限定在 use()块内，所以也就限定于当前执行的线程。进入该 use()块内的代码会在当前线程创建一个栈帧，并压入到当前线程的栈上，而当 use 代码块结束后，当前线程的栈会将刚刚压入的栈帧弹栈。但是如果频繁的调用 use 代码块，势必会对性能造成一定的影响。</p>
<p>凡事都有两面性，Categoty 的使用 use 块，提供了更好的隔离性，我们可以再不同的地方，使用不同的分类，这也为类的扩展提供了灵活性。</p>
</li>
<li><p>trait：缺点是在有类的修改权的情况下才能使用，类似接口。</p>
</li>
<li><p>Mixin：其实是最强大的方式，但需要对其有进一步的了解，以防走火。。</p>
</li>
</ul>
<p>这里推荐使用 <strong>ExpandoMetaClass。</strong></p>


    </div>









      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    zachaxy
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://zachaxy.github.io/2017/12/10/MOP——方法注入/" title="MOP——方法注入">https://zachaxy.github.io/2017/12/10/MOP——方法注入/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>


    <footer class="post-footer">

        <div class="post-tags">

            <a href="/tags/Groovy/" rel="tag"># Groovy</a>

        </div>







        <div class="post-nav">
          <div class="post-nav-next post-nav-item">

              <a href="/2017/12/09/MOP——方法拦截/" rel="next" title="MOP——方法拦截">
                <i class="fa fa-chevron-left"></i> MOP——方法拦截
              </a>

          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">

              <a href="/2017/12/11/MOP——方法合成/" rel="prev" title="MOP——方法合成">
                MOP——方法合成 <i class="fa fa-chevron-right"></i>
              </a>

          </div>
        </div>




    </footer>
  </div>



  </article>



    <div class="post-spread">

    </div>
  </div>


          </div>









        </div>



  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">

      <div id="sidebar-dimmer"></div>

    <div class="sidebar-inner">




        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>


      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">

              <img class="site-author-image" itemprop="image" src="/images/avatar.jpg" alt="zachaxy">

              <p class="site-author-name" itemprop="name">zachaxy</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">


              <div class="site-state-item site-state-posts">

                <a href="/archives">

                  <span class="site-state-item-count">64</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>







              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">12</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>


          </nav>



          <div class="links-of-author motion-element">


                <span class="links-of-author-item">
                  <a href="https://github.com/zachaxy" target="_blank" title="GitHub">

                      <i class="fa fa-fw fa-globe"></i>GitHub</a>
                </span>

                <span class="links-of-author-item">
                  <a href="https://weibo.com/3242765540" target="_blank" title="Weibo">

                      <i class="fa fa-fw fa-globe"></i>Weibo</a>
                </span>


          </div>









        </div>
      </section>


      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">






              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#方法拦截和方法注入的区别"><span class="nav-number">1.</span> <span class="nav-text">方法拦截和方法注入的区别</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#使用分类进行方法注入"><span class="nav-number">2.</span> <span class="nav-text">使用分类进行方法注入</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#使用-ExpandoMetaClass-进行方法注入"><span class="nav-number">3.</span> <span class="nav-text">使用 ExpandoMetaClass 进行方法注入</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#注入概述"><span class="nav-number">3.1.</span> <span class="nav-text">注入概述</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#注入的种类"><span class="nav-number">3.2.</span> <span class="nav-text">注入的种类</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#向单个实例中注入方法"><span class="nav-number">3.3.</span> <span class="nav-text">向单个实例中注入方法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#ExpandoMetaClass-小结"><span class="nav-number">3.4.</span> <span class="nav-text">ExpandoMetaClass 小结</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#使用-Minxin，trait-进行方法注入"><span class="nav-number">4.</span> <span class="nav-text">使用 Minxin，trait 进行方法注入</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#实现方式的优劣对比"><span class="nav-number">5.</span> <span class="nav-text">实现方式的优劣对比</span></a></li></ol></div>


          </div>
        </section>
      <!--/noindex-->




    </div>
  </aside>



      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">zachaxy</span>


    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>

      <span class="post-meta-item-text">站点文章字数总计&#58;</span>

    <span title="站点文章字数总计">147.9k</span>

</div>






  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a></div>













      </div>
    </footer>


      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>

          <span id="scrollpercent"><span>0</span>%</span>

      </div>




  </div>



<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>
























    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>




    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>




    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>




    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>




    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>




    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>






  <script type="text/javascript" src="/js/src/utils.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.3"></script>







  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.3"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.3"></script>






  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.3"></script>







































  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>

















  <script type="text/javascript" src="/js/src/js.cookie.js?v=5.1.3"></script>
  <script type="text/javascript" src="/js/src/scroll-cookie.js?v=5.1.3"></script>





</body>
</html>
